package com.itheima.info.manage.system.dao;

import com.itheima.info.manage.system.domain.Student;

/*
增
删
改
查


 */
public class StudentDao implements BaseStudentDao {
    private static Student[] stus = new Student[50];
    static {
        Student cai = new Student("0001", "小蔡", 28, "1992-01-01");
        Student lu = new Student("0002", "小鹿", 30, "1992-01-01");
        Student wu = new Student("0003", "小吴", 31, "1992-01-01");
        Student huang = new Student("0004", "小黄", 28, "1992-01-01");
        stus[0]=cai;
        stus[1]=lu;
        stus[2]=wu;
        stus[3]=huang;


    }
    public boolean addStudent(Student student) {
        //获取数组 向数组中添加元素

        //遍历数组
        for (int i = 0; i < stus.length; i++) {
            Student stu = stus[i];
            //找空位 如果是null 可以存
            if (stu == null) {
                stus[i] = student;
                return true;
            }
        }
        //最后都没找到
        return false;
    }

    /*
    查询所有的学生
     */
    public Student[] findAllStudents() {
        return stus;
    }

    public void deleteStudentBySid(String sid) {
        //根据 索引来删除
        int index = getIndex(sid);
        stus[index] = null;

    }

    //根据sid 找索引
    public int getIndex(String sid) {
        //遍历数组
        for (int i = 0; i < stus.length; i++) {
            Student stu = StudentDao.stus[i];
            //判断学号是否相同
            if (stu != null && stu.getSid().equals(sid)) {
                //相同 返回 索引
                return i;
            }
        }
        //所有都不同 返回 -1
        return -1;
    }

    public void updateStudent(String sid, Student newStu) {
        int index = getIndex(sid);
        stus[index] = newStu;

    }
}
